<template>
  <div id="container" ref="container"></div>
</template>

<script setup>
import { ElSwitch, ElTabs,ElTabPane,ElMessage } from 'element-plus';
import Detail from './Detail.vue'
import AMapLoader from '@amap/amap-jsapi-loader';
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

const props = defineProps({
  data: {
    type: Object,
    default: () => ([]),
  },
})

watch(() => props.data, (val, old) => {
  initMap()
}, {
  deep: true
})

const aMap = ref(null)
const map = ref(null)
const overlays = ref([])
const marker = ref(null) // 东北点经纬度
const infoWindow = ref() // 自定义信息弹窗
const container = ref()

const initMap = () => {
  AMapLoader.load({
    key: "54aec802ee2b6caec09514ea932dd1d6", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    if (!map.value) {
      map.value = new AMap.Map("container", {
        // 设置地图容器id
        viewMode: '3D', // 是否为3D地图模式,必须使用 3D 模式才能旋转
        zoom: 20, // 初始化地图级别
        zoomEnable: false, // 地图是否可缩放，默认值为true
        scrollWheel: false, // 禁用鼠标滚轮,不然InfoWindow内部overflow-y: auto;无法滚动
        center: [userStore.stationInfo.deviceLng || userStore.stationInfo.lng, userStore.stationInfo.deviceLat || userStore.stationInfo.lat], // 初始化地图中心点位置
        layers: [ // 卫星地图
          new AMap.TileLayer.Satellite()
        ]
      });
      if (map.value) {
        aMap.value = AMap
      }
    }

    // 清除所有覆盖物
    map.value.clearMap();
    overlays.value = []

    let arr = JSON.parse(JSON.stringify(props.data))
    arr.forEach((item,index) => {
      handleCreateRectangle(item,index)
    })

    map.value.on('click', function (e) {
      if (infoWindow.value) {
        infoWindow.value.close()
      }
    })
  }).catch(e => {
  })
}

// 添加实例化点标记
const addMarker = (lng, lat) => {
  if (marker.value) {
    marker.value.setMap(null)
    marker.value = null
  }
  if (!marker.value) {
    marker.value = new aMap.value.Marker({
      icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
      position: [lng, lat],
      anchor: 'bottom-center'
    })
    marker.value.setMap(map.value)
    // map.value.setZoomAndCenter(15, [lng, lat]);
  }
}

// 添加矩形覆盖物
const handleCreateRectangle = (item,index) => {
  if (!item.markerLocation) return
  // deviceRunStatus 运行状态 1 离线 2 关闭 3 运行中
  // deviceShowStatus 显示状态 1 预警 2 离线 3 正常 4 告警
  // powerStatus 功率状态 1正常(较高) 2 预警(正常) 3 告警(偏低) 4 关闭

  let fillColor = ''
  if (item.powerStatus == 1) {
    fillColor = '#347caf'
  } else if (item.powerStatus == 2) {
    fillColor = '#4095e5'
  } else if (item.powerStatus == 3) {
    fillColor = '#93d2f3'
  } else if (item.powerStatus == 4) {
    fillColor = '#cecece'
  }
  const polygonPath = item.polygonLocation?item.polygonLocation.map(location => {
    let arr = JSON.parse(JSON.stringify(location))
    arr[0] = Number(arr[0])
    arr[1] = Number(arr[1])
    return arr
  }):[]
  const polygon = new aMap.value.Polygon({
    path: polygonPath,
    strokeColor: '#ffffff',
    strokeOpacity: 1,
    strokeWeight: 2,
    fillColor,
    fillOpacity: 1,
    strokeStyle: 'solid',
    cursor:'pointer',
  });
  map.value.add(polygon); // 多边形实例添加到地图显示
  item.polygon = item.polygon // 多边形实例
  overlays.value.push(item);

  const markerPosition = item.markerLocation?item.markerLocation.map(location => {
    location = Number(location)
    return location
  }):[]
  const marker = new aMap.value.Marker({
    position: markerPosition,
    content: `
      <div style="transform: rotate(${item.angle}deg);" class="device-name">${item.logicAddress}</div>
    `,
    anchor: 'center',
    cursor: 'pointer',
  });
  map.value.add(marker); // marker实例添加到地图显示
  item.marker = item.marker // marker实例
  overlays.value.push(item);

  const roundPosition = item.roundLocation?item.roundLocation.map(location => {
    location = Number(location)
    return location
  }):[]
  const round = new aMap.value.Marker({
    position: roundPosition,
    content: `
      <div class="device-status on-${item.deviceShowStatus}"></div>
    `,
    anchor: 'center',
    cursor: 'pointer',
  });
  map.value.add(round); // marker实例添加到地图显示
  item.round = item.round // marker实例
  overlays.value.push(item);

  polygon.on('click', function (e) {
    handleInfoWindow(item)
  })
  marker.on('click', function (e) {
    handleInfoWindow(item)
  })
  round.on('click', function (e) {
    handleInfoWindow(item)
  })
}

// 添加自定义信息窗口
const handleInfoWindow = (item) => {
  if(!item) {
    ElMessage({ message: '暂无组件信息,请联系管理员配置组件~', type: 'warning' })
    return
  }
  const contentDiv = document.createElement('div');
  // 创建独立 Vue 应用
  const detailApp = createApp(Detail,{deviceInfo:item});
  // detailApp.component(ElSwitch.name, ElSwitch);  // 注入 Element Plus 组件
  // detailApp.component(ElTabs.name, ElTabs);
  // detailApp.component(ElTabPane.name, ElTabPane);
  // 挂载到临时容器
  detailApp.mount(contentDiv);
  // InfoWindow的content不支持渲染element的组件,需要使用createApp单独创建一个vue应用并注入 Element Plus 组件
  infoWindow.value = new aMap.value.InfoWindow({
    isCustom: true,  //使用自定义窗体
    content:contentDiv,
    offset: new aMap.value.Pixel(0, -16)
  });
  infoWindow.value.open(map.value, item.markerLocation);
}

const openInfoWindow = (e) => {
  let deviceItem = overlays.value.find(item => item.deviceId==e.deviceId)
  if(e.deviceId) {
    handleInfoWindow(deviceItem)
  }
}

onMounted(() => {
  initMap()
})
onBeforeUnmount(() => {
  map.value?.destroy();
})

defineExpose({
  openInfoWindow
})
</script>

<style lang="scss" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
}

:deep(.device-name) {
  color: #ffffff;
  font-size: 10px;
}

:deep(.device-status) {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 1px solid #ffffff;
  &.on-1 {
    background-color: #e99d42;
  }

  &.on-2 {
    background-color: #cecece;
  }

  &.on-3 {
    // background-color: #a2ef4d;
    background-color: #32C275;
  }
  &.on-4 {
    background-color: #fd0909;
  }
}

.device-slider {
  display: flex;
  align-items: center;
  height: 40px;

  .slider-left {
    margin-right: 20px;
  }
}
</style>
